"use strict";
var smsTxt;
$(function () {
    $(".alert").hide();
    smsTxt = $("#smsTxt").val();
    updateTxtLength();
    $("#intevDate").on("input propertychange",function () {
        updateSmsTxt();
        updateState();
    });
    $("#contact").on("input propertychange",function () {
        updateSmsTxt();
        updateState();
    });
    $("#phoneNum").on("input propertychange",function () {
        updateState();
    });

})

function updateState() {
    var phoneNum     = $("#phoneNum").val();
    var intevDateLen = $("#intevDate").val().trim().length;
    var contactLen   = $("#contact").val().trim().length;
    var isphoneNumOk = /^1[34578]\d{9}$/.test(phoneNum);
    !isphoneNumOk?$("#phoneNum").parent().addClass("has-error has-feedback"):$("#phoneNum").parent().removeClass("has-error has-feedback");
    intevDateLen<=0?$("#intevDate").parent().addClass("has-error has-feedback"):$("#intevDate").parent().removeClass("has-error has-feedback");
    contactLen<=0?$("#contact").parent().addClass("has-error has-feedback"):$("#contact").parent().removeClass("has-error has-feedback");
    var isOk = isphoneNumOk&&intevDateLen&&contactLen;
    updateSendBtn(isOk);

    return isOk;
}
function updateSendBtn(isOk) {
    if(isOk){
        $("#send_btn").removeClass("disabled");
    }else{
        $("#send_btn").addClass("disabled");
    }
}

function sendSms() {
    if(updateState()){
        updateSendBtn(false);
        var param = $("#smsform").serialize();
        $.ajax({
            type:"POST",
            url:"sms/smsSend",
            data:param,
            success: function(data){
                if(data.msg){//非json表示session失效
                    showAlert(data.msg);
                    if(data.state>0)$("#phoneNum").val("");
                }else{
                    $("#sms_root").html(data);
                }
            },
            error:function () {
                showAlert("请求错误!");
            },
            complete:function () {
                updateSendBtn(true);
            }
        });
    }
}

function showAlert(msg) {
    $("#alert_content").text(msg);
    $(".alert").show("slow");
    setTimeout(function () {
        $(".alert").hide("slow");
    },1500);
}

function updateSmsTxt() {
    var txt = smsTxt.replace("${date}",$("#intevDate").val());
    txt = txt.replace("${name}",$("#contact").val());
    $("#smsTxt").val(txt);
    updateTxtLength();
}

function updateTxtLength() {
    $("#smslenth").text($("#smsTxt").val().trim().length+"/68字");
}
